package com.hlf.common.utils.wx;

import com.alibaba.druid.util.StringUtils;
import com.hlf.common.utils.SpringContextUtils;
import com.hlf.modules.wechat.model.ConfigWechat;
import com.hlf.modules.wechat.model.OfficialAccount;
import com.hlf.modules.wechat.service.ConfigWechatService;
import com.hlf.modules.wechat.service.OfficialAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author suyangsheng
 * @date 2017年3月13日 上午10:25:01
 */
public class AccessTokenUtil {

    private static Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);

    private static OfficialAccountService oaService = SpringContextUtils.getBean("officialAccountServiceImpl", OfficialAccountService.class);

    private static ConfigWechatService configWechatService = SpringContextUtils.getBean("configWechatServiceImpl", ConfigWechatService.class);

    public static String initAndSetAccessToken() {
        logger.info("开始初始化accesstoken 时间戳{}", System.currentTimeMillis());
        String accessToken = null;
        try {
            // 缓存公众号accessToken和jsapi调用凭证
            accessToken = initAccessToken();
        } catch (Exception e) {
            logger.error("=======================初始化accesstoken异常，时间戳 {}", System.currentTimeMillis(), e);
        }
        logger.info("结束初始化accesstoken 时间戳{}", System.currentTimeMillis());
        return accessToken;
    }

    private static String initAccessToken() {
        List<ConfigWechat> configWechats = configWechatService.select();
        for (ConfigWechat configWechat : configWechats) {
            if (configWechat == null) {
                logger.info("获取微信配置信息为空");
                return null;
            }
            String appid = configWechat.getAppId();
            String originalId = configWechat.getOriginalId();
            String appsecret = configWechat.getAppSecret();
            if (!StringUtils.isEmpty(appid) && !StringUtils.isEmpty(originalId)) {
                Token accessToken = WxUtils.getAccessToken(appid, appsecret);
                if (null != accessToken && accessToken.getAccessToken() != null) {
                    // 向数据库中更新access_token
                    OfficialAccount oa = oaService.selectByOriginalId(originalId);
                    logger.info("根据originalId:{}查询到的OfficialAccount:{}", originalId, oa);
                    OfficialAccount oaUpdate = new OfficialAccount();
                    oaUpdate.setId(oa.getId());
                    oaUpdate.setToken(accessToken.getAccessToken());
                    oaService.updateByIdSelective(oaUpdate);
                    return accessToken.getAccessToken();
                }
            }
        }
        return null;
    }

}
